//
//  showFileVC.m
//  SQLiteTesting
//
//  Created by kitinat on 1/30/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//

#import "showFileVC.h"
#import "EGAAppDelegate.h"

@interface showFileVC ()

@end

@implementation showFileVC

@synthesize fileInfo;


@synthesize showFileWebView;
@synthesize TalkOrTask;


@synthesize receivedData;

@synthesize navBar;
@synthesize lbFileTitle;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self dismissKeyboard];
    
    
    //set constant
    NSArray     * arrFileInfo           = [fileInfo componentsSeparatedByString:@"|"];
    NSString    * fileID                = arrFileInfo[0];
    NSString    * fileNameAndType       = arrFileInfo[1];
    NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
    //NSString    * fileName              = arrFileNameAndType[0];
    NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
    
    //set navbar title
    lbFileTitle.text = [NSString stringWithFormat:@"[เอกสาร] %@", fileNameAndType];
    
    //set name of file that save in local document path
    NSString    * storeFileName;
    if ([@"task" isEqualToString:TalkOrTask])
        storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
    
    if ([@"talk" isEqualToString:TalkOrTask])
        storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"talk",fileID,fileType];

    
    
    //check if file exist or not
    if([self isHasFileWithSavedFileName:storeFileName])
    {
        [self showFileWithsavedFileName:storeFileName];
    }
    else
    {
        if([self internetConnected])
        {
            //set url
            NSString *urlAddress;
            if ([@"task" isEqualToString:TalkOrTask])
            {
                ///urlAddress = [@"http://172.17.31.21/Arc_ShowFile.aspx?File_Attach_ID=" stringByAppendingString:fileID];
                urlAddress = [@"http://164.115.5.192/Archive/Arc_ShowFile.aspx?File_Attach_ID=" stringByAppendingString:fileID];
            }
            if ([@"talk" isEqualToString:TalkOrTask])
            {
                //urlAddress = [NSString stringWithFormat: @"http://172.17.31.21/Arc_ShowUploadedFile.aspx?from=ios&Arc_Doc_Talk_File_ID=%@",fileID];
                urlAddress = [NSString stringWithFormat: @"http://164.115.5.192/Archive/Arc_ShowUploadedFile.aspx?from=ios&Arc_Doc_Talk_File_ID=%@",fileID];
            }
            [self downloadAndSavedFileWithUrl:urlAddress savedFileName:storeFileName];
            [self showFileWithsavedFileName:storeFileName];
        }
        else
        {
            [self alertNotConnect];
        }
        
    }
    
}









#pragma dismisskeyboard
- (void)dismissKeyboard {
    [self globalResignFirstResponder];
}
- (void) globalResignFirstResponder {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    for (UIView * view in [window subviews]){
        [self globalResignFirstResponderRec:view];
    }
}
- (void) globalResignFirstResponderRec:(UIView*) view {
    if ([view respondsToSelector:@selector(resignFirstResponder)]){
        [view resignFirstResponder];
    }
    for (UIView * subview in [view subviews]){
        [self globalResignFirstResponderRec:subview];
    }
}










-(BOOL)isHasFileWithSavedFileName:(NSString*)savedFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //if file not exist in document
    if([fileManager fileExistsAtPath:writablePath])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
- (BOOL)internetConnected
{
    //NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://172.17.31.21/"]];
    NSString *strURL = [NSString stringWithFormat:@"http://164.115.5.192/"];
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:strURL]];
    return ( URLString != NULL ) ? YES : NO;
}



-(void)downloadAndSavedFileWithUrl:(NSString*)strUrl savedFileName:(NSString*)savedFileName
{
    NSURL *URL = [NSURL URLWithString:strUrl];
    
    NSData *dtFile = [[NSData alloc] initWithContentsOfURL:URL];
    
    //set local file path
    NSArray  * arrDocDBPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString * documentsDirectory = [arrDocDBPath objectAtIndex:0];
    NSString * strDocDBPath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //save
    [dtFile writeToFile:strDocDBPath atomically:YES];
}
-(void)showFileWithsavedFileName:(NSString*)savedFileName
{
    NSArray  * arrDocDBPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString * documentsDirectory = [arrDocDBPath objectAtIndex:0];
    NSString * strDocDBPath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"];
    NSURL *targetURL = [NSURL fileURLWithPath:strDocDBPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [showFileWebView loadRequest:request];
}
-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถดาวน์โหลดเอกสาร"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}




























- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc {
    [super dealloc];
}
@end
